// DOM元素引用
const mainView = document.getElementById('main-view');
const editView = document.getElementById('edit-view');
const addNewBtn = document.getElementById('add-new');
const backBtn = document.getElementById('back-btn');
const cancelBtn = document.getElementById('btn-cancel');
const saveBtn = document.getElementById('btn-save');
const searchInput = document.getElementById('search-input');
const regionFilter = document.getElementById('region-filter');
const searchBtn = document.getElementById('search-btn');
const viewBtns = document.querySelectorAll('.btn-view');
const copyBtns = document.querySelectorAll('.btn-copy');
const editBtns = document.querySelectorAll('.btn-edit');
const regionHeaders = document.querySelectorAll('.region-header');

// 凭据数据
let credentialsData = {
  credentials: []
};

// 从chrome.storage加载数据
function loadCredentialsData() {
  chrome.storage.sync.get(['credentials'], function(result) {
    if (result.credentials) {
      credentialsData.credentials = result.credentials;
    } else {
      // 如果storage中没有数据，初始化空数组
      credentialsData.credentials = [];
      // 保存初始空数据到storage
      saveToStorage();
    }
    renderCredentialsList();
    // 加载完凭据数据后，更新地区选项
    loadRegionOptions();
  });
}

// 从凭据数据中提取唯一地区列表并更新筛选下拉框
function loadRegionOptions() {
  // 获取所有唯一的地区
  const regions = [...new Set(credentialsData.credentials.map(cred => cred.region))];
  
  // 清除现有的选项（除了"全部"选项）
  while (regionFilter.options.length > 1) {
    regionFilter.remove(1);
  }
  
  // 添加地区选项
  regions.forEach(region => {
    const option = document.createElement('option');
    option.value = region; // 直接使用地区名称作为值，不再转换
    option.textContent = region;
    regionFilter.appendChild(option);
  });
}

// 保存数据到chrome.storage
function saveToStorage() {
  chrome.storage.sync.set({credentials: credentialsData.credentials}, function() {
    console.log('凭据已保存到storage');
  });
}

// 渲染凭据列表
function renderCredentialsList() {
  // 清空现有列表
  const credentialsList = document.querySelector('.credentials-list');
  credentialsList.innerHTML = '';
  
  // 按地区分组
  const regionGroups = {};
  credentialsData.credentials.forEach(credential => {
    if (!regionGroups[credential.region]) {
      regionGroups[credential.region] = [];
    }
    regionGroups[credential.region].push(credential);
  });
  
  // 为每个地区创建组
  for (const region in regionGroups) {
    const regionGroup = document.createElement('div');
    regionGroup.className = 'region-group';
    
    const regionHeader = document.createElement('div');
    regionHeader.className = 'region-header';
    regionHeader.innerHTML = `<i class="fas fa-chevron-down"></i><span>${region}</span>`;
    regionHeader.addEventListener('click', () => toggleRegionItems(regionHeader));
    
    const regionItems = document.createElement('div');
    regionItems.className = 'region-items';
    
    // 添加该地区的每个凭据项
    regionGroups[region].forEach(credential => {
      const item = createCredentialItem(credential);
      regionItems.appendChild(item);
    });
    
    regionGroup.appendChild(regionHeader);
    regionGroup.appendChild(regionItems);
    credentialsList.appendChild(regionGroup);
  }
  
  // 重新绑定按钮事件
  document.querySelectorAll('.btn-view').forEach(btn => {
    btn.addEventListener('click', () => {
      const passwordSpan = btn.closest('.credential-item').querySelector('.password');
      togglePasswordVisibility(btn, passwordSpan);
    });
  });
  
  document.querySelectorAll('.btn-copy').forEach(btn => {
    btn.addEventListener('click', () => {
      const item = btn.closest('.credential-item');
      const username = item.querySelector('.username').textContent;
      const region = item.closest('.region-group').querySelector('.region-header span').textContent;
      const credential = credentialsData.credentials.find(c => c.username === username && c.region === region);
      
      if (credential) {
        copyToClipboard(credential.password);
      }
    });
  });
  
  document.querySelectorAll('.btn-edit').forEach(btn => {
    btn.addEventListener('click', () => {
      const item = btn.closest('.credential-item');
      const username = item.querySelector('.username').textContent;
      const region = item.closest('.region-group').querySelector('.region-header span').textContent;
      
      editCredential(username, region);
    });
  });
  
  // 重新绑定地区头部事件
  document.querySelectorAll('.region-header').forEach(header => {
    header.addEventListener('click', () => toggleRegionItems(header));
  });
}

// 创建单个凭据项的DOM元素
function createCredentialItem(credential) {
  const item = document.createElement('div');
  item.className = 'credential-item';
  
  const info = document.createElement('div');
  info.className = 'credential-info';
  info.innerHTML = `
    <span class="username">${credential.username}</span>
    <span class="password" data-visible="false">${'*'.repeat(credential.password.length)}</span>
  `;
  
  const actions = document.createElement('div');
  actions.className = 'credential-actions';
  actions.innerHTML = `
    <button class="btn-view" title="查看密码"><i class="fas fa-eye"></i></button>
    <button class="btn-copy" title="复制密码"><i class="fas fa-clipboard"></i></button>
    <button class="btn-edit" title="编辑"><i class="fas fa-edit"></i></button>
  `;
  
  item.appendChild(info);
  item.appendChild(actions);
  return item;
}

// 编辑凭据
function editCredential(username, region) {
  const credential = credentialsData.credentials.find(c => c.username === username && c.region === region);
  
  if (credential) {
    // 填充表单
    document.getElementById('input-username').value = credential.username;
    document.getElementById('input-password').value = credential.password;
    document.getElementById('input-region').value = credential.region;
    document.getElementById('input-note').value = credential.note || '';
    
    // 记录正在编辑的凭据ID
    document.getElementById('input-username').dataset.id = credential.id;
    
    showEditView();
  }
}

// 视图切换
function showEditView() {
  mainView.classList.add('hidden');
  editView.classList.remove('hidden');
}

function showMainView() {
  editView.classList.add('hidden');
  mainView.classList.remove('hidden');
}

// 显示或隐藏密码
function togglePasswordVisibility(btn, passwordSpan) {
  const isVisible = passwordSpan.dataset.visible === 'true';
  
  if (isVisible) {
    const passwordText = passwordSpan.getAttribute('data-password');
    passwordSpan.textContent = '*'.repeat(passwordText.length);
    passwordSpan.dataset.visible = 'false';
    btn.innerHTML = '<i class="fas fa-eye"></i>';
  } else {
    // 从存储中获取原始密码
    const username = passwordSpan.previousElementSibling.textContent;
    const region = passwordSpan.closest('.region-group').querySelector('.region-header span').textContent;
    const credential = credentialsData.credentials.find(c => c.username === username && c.region === region);
    
    if (credential) {
      passwordSpan.textContent = credential.password;
      passwordSpan.setAttribute('data-password', credential.password);
      passwordSpan.dataset.visible = 'true';
      btn.innerHTML = '<i class="fas fa-eye-slash"></i>';
    }
  }
}

// 复制到剪贴板
function copyToClipboard(text) {
  navigator.clipboard.writeText(text).then(() => {
    // 显示复制成功提示
    alert('已复制到剪贴板');
  }).catch(err => {
    console.error('复制失败:', err);
  });
}

// 切换地区组显示/隐藏
function toggleRegionItems(header) {
  const items = header.nextElementSibling;
  const icon = header.querySelector('i');
  
  if (items.style.display === 'none') {
    items.style.display = 'block';
    icon.className = 'fas fa-chevron-down';
  } else {
    items.style.display = 'none';
    icon.className = 'fas fa-chevron-right';
  }
}

// 搜索功能
function handleSearch() {
  const searchTerm = searchInput.value.toLowerCase();
  const selectedRegion = regionFilter.value;
  
  document.querySelectorAll('.credential-item').forEach(item => {
    const username = item.querySelector('.username').textContent.toLowerCase();
    const regionGroup = item.closest('.region-group');
    const region = regionGroup.querySelector('.region-header span').textContent;
    
    const matchesSearch = username.includes(searchTerm);
    const matchesRegion = selectedRegion === 'all' || region === selectedRegion;
    
    if (matchesSearch && matchesRegion) {
      item.style.display = 'flex';
      regionGroup.style.display = 'block';
    } else {
      item.style.display = 'none';
    }
  });
  
  // 隐藏空的地区组
  document.querySelectorAll('.region-group').forEach(group => {
    const hasVisibleItems = Array.from(group.querySelectorAll('.credential-item')).some(item => 
      item.style.display !== 'none'
    );
    
    if (!hasVisibleItems) {
      group.style.display = 'none';
    }
  });
}

// 生成唯一ID
function generateUniqueId() {
  return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
}

// 添加或更新凭据
function saveCredential() {
  const usernameInput = document.getElementById('input-username');
  const username = usernameInput.value;
  const password = document.getElementById('input-password').value;
  const region = document.getElementById('input-region').value;
  const note = document.getElementById('input-note').value;
  const id = usernameInput.dataset.id || generateUniqueId();
  
  if (!username || !password || !region) {
    alert('请填写必填字段');
    return;
  }
  
  // 检查是否是编辑现有凭据
  const existingIndex = credentialsData.credentials.findIndex(c => c.id === id);
  
  if (existingIndex !== -1) {
    // 更新现有凭据
    credentialsData.credentials[existingIndex] = {
      id,
      username,
      password,
      region,
      note
    };
  } else {
    // 添加新凭据
    credentialsData.credentials.push({
      id,
      username,
      password,
      region,
      note
    });
  }
  
  // 保存到storage
  saveToStorage();
  
  // 清空表单
  usernameInput.value = '';
  document.getElementById('input-password').value = '';
  document.getElementById('input-region').value = '';
  document.getElementById('input-note').value = '';
  delete usernameInput.dataset.id;
  
  // 重新渲染列表
  renderCredentialsList();
  
  // 更新地区选项
  loadRegionOptions();
  
  // 返回主视图
  showMainView();
  
  alert('保存成功');
}

// 事件监听
addNewBtn.addEventListener('click', () => {
  // 清空表单，准备添加新凭据
  document.getElementById('input-username').value = '';
  document.getElementById('input-password').value = '';
  document.getElementById('input-region').value = '';
  document.getElementById('input-note').value = '';
  delete document.getElementById('input-username').dataset.id;
  
  showEditView();
});

backBtn.addEventListener('click', showMainView);
cancelBtn.addEventListener('click', showMainView);

searchBtn.addEventListener('click', handleSearch);
searchInput.addEventListener('input', handleSearch);
regionFilter.addEventListener('change', handleSearch);

saveBtn.addEventListener('click', saveCredential);

// 初始加载数据
document.addEventListener('DOMContentLoaded', loadCredentialsData); 